﻿using IOP.Extension.DependencyInjection;
using IOP.SgrA;
using IOP.SgrA.Input;
using IOP.SgrA.SilkNet.Vulkan;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Silk.NET.Vulkan;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;

namespace VkSample101
{
    public class Middleware : IProductionLineMiddleware<SecondaryVulkanRenderGroup>
    {
        [Autowired]
        private ILogger<Middleware> _Logger { get; set; }

        public void Invoke(SecondaryVulkanRenderGroup group, RenderingProductionLineDelegate<SecondaryVulkanRenderGroup> next)
        {
            try
            {
                var camera = group.Camera;
                var view = camera.ViewMatrix;
                var project = camera.ProjectionMatrix;
                var cmd = group.SecondaryCommandBuffer;

                CommandBufferInheritanceInfo info = new CommandBufferInheritanceInfo
                {
                    Framebuffer = group.Framebuffer.RawHandle,
                    OcclusionQueryEnable = false,
                    RenderPass = group.RenderPass.RawHandle,
                    Subpass = 0
                };
                cmd.Reset();
                cmd.Begin(CommandBufferUsageFlags.CommandBufferUsageOneTimeSubmitBit | 
                    CommandBufferUsageFlags.CommandBufferUsageRenderPassContinueBit, info);
                cmd.BindPipeline(PipelineBindPoint.Graphics, group.Pipeline);

                var viewPort = camera.Viewport;
                var scissor = camera.Scissor;
                cmd.SetViewport(new Viewport(viewPort.X, viewPort.Y, viewPort.Width, viewPort.Height, viewPort.MinDepth, viewPort.MaxDepth));
                cmd.SetScissor(new Rect2D(new Offset2D(scissor.X, scissor.Y), new Extent2D(scissor.Width, scissor.Height)));

                foreach (var item in group.GetContexts())
                {
                    item.SetViewMatrix(in view);
                    item.SetProjectionMatrix(in project);
                    item.SetCamera(camera);
                    group.ItemProductionLine(item);
                }
                cmd.End();
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message + "\r\n" + e.StackTrace);
                group.Disable();
            }
        }
    }
}
